package com.example.ssss;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ssss.data.IotdbOperation;
import com.example.ssss.data.MyMqttService;
import com.example.ssss.data.entity.Behave;
import com.example.ssss.data.entity.Env;
import com.example.ssss.data.entity.MyMqttMessage;
import com.example.ssss.data.entity.ShareData;
import com.example.ssss.data.entity.Threshold;
import com.example.ssss.data.entity.TimeStamp;
import com.example.ssss.data.entity.Wear;
import com.example.ssss.data.util.JsonParse;
import com.example.ssss.databinding.ActivityDrivingDetectionBinding;
import com.example.ssss.request.DrivingDetectionRequestViewModel;
import com.example.ssss.state.DrivingDetectionStateViewModel;
import com.zlylib.slidetogglelib.SlideToggleView;

import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;

import java.util.HashMap;

public class DrivingDetectionActivity extends AppCompatActivity {

    private Chronometer drivingTimer;
    private AlertDialog alertDialog=null;
    //三个按钮和它们的动画
    TextView tv1;
    TextView tv2;
    TextView tv3;
    private ValueAnimator apperaAnim1;
    private ValueAnimator hiddenAnim1;
    private ValueAnimator apperaAnim2;
    private ValueAnimator hiddenAnim2;
    private ValueAnimator apperaAnim3;
    private ValueAnimator hiddenAnim3;
    private boolean ISSTARTUP = false;
    DrivingDetectionStateViewModel stateViewModel;
    DrivingDetectionRequestViewModel requestViewModel;
    ActivityDrivingDetectionBinding binding;
    MyMqttService mqttService;
    MyMqttServiceConn myServiceConn;
    MyMqttService.LocalBinder binder = null;
    private Intent bindIntent = null;
    SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
    HashMap<Integer, Integer> soundPoolMap = new HashMap<Integer, Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持屏幕常量
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_driving_detection);
        this.setTitle("正在驾驶");

        // 数据绑定，ViewModel绑定
        stateViewModel = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(DrivingDetectionStateViewModel.class);
        requestViewModel = new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(DrivingDetectionRequestViewModel.class);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_driving_detection);
        binding.setVm(stateViewModel);
        binding.setLifecycleOwner(this);
        mqttService = new MyMqttService();

        //服务绑定
        bindIntent = new Intent(this,MyMqttService.class);
        myServiceConn = new DrivingDetectionActivity.MyMqttServiceConn();
        bindService(bindIntent,myServiceConn, Context.BIND_AUTO_CREATE);


        /*****业务逻辑*****/
        // 开启wear和env
        //mqttService.publish("ESP32_wear_W0001_on","1");
        mqttService.publish("ESP32_env_E0001_3","1");
        mqttService.publish("switch_behave_on_04EA56902CB0","1");

        /*****初始化*****/
        initStateViewModel();

        /*****开始计时*****/
        drivingTimer= binding.drivingTime;
        onRecordStart(drivingTimer);


        /*****动画*****/
        //设置暂停完成继续三个按钮的动画
        tv1=binding.tv1; tv2=binding.tv2; tv3=binding.tv3;
        setDrivingBtnListener(tv1);setDrivingBtnListener(tv2);setDrivingBtnListener(tv3);

        //设置紧急呼叫监听
        SlideToggleView slideToggleView = findViewById(R.id.slideToggleView);
        slideToggleView.setSlideToggleListener(new SlideToggleView.SlideToggleListener() {
            @Override
            public void onBlockPositionChanged(SlideToggleView view, int left, int total, int slide) {
                /**
                 * 滑块位置改变回调
                 *
                 * @param left  滑块左侧位置，值等于{@link #getLeft()}
                 * @param total 滑块可以滑动的总距离
                 * @param slide 滑块已经滑动的距离
                 */

            }
            @Override
            public void onSlideListener(SlideToggleView view, int leftOrRight) {
                /**
                 * 滑动打开
                 *  @param leftOrRight  0 左边
                 *  @param leftOrRight  1 右边
                 */
                if(leftOrRight==1){
//                    startSOSCard();
                    sentSOSDialog();
                }
            }
        });

        //初始化音频
        initSound();
    }
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            setApperaAnimationView();
            setHiddenAnimationView();
            hiddenAnim1.start();hiddenAnim3.start();apperaAnim2.start();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    private void initStateViewModel(){
        stateViewModel.setBehaveState(false);
        stateViewModel.setHighPressureState(false);
        stateViewModel.setLowPressureState(false);
        stateViewModel.setHeartBeatState(false);
        stateViewModel.setBloodOxygenState(false);
        stateViewModel.setEnvCO2State(false);
        stateViewModel.setEnvHumidityState(false);
        stateViewModel.setEnvTemperatureState(false);
        stateViewModel.setEnvTVOCState(false);
        stateViewModel.setBehaveText(this.getString(R.string.detection_default));
        stateViewModel.setHighPressureText(this.getString(R.string.detection_default));
        stateViewModel.setLowPressureText(this.getString(R.string.detection_default));
        stateViewModel.setHeartBeatText(this.getString(R.string.detection_default));
        stateViewModel.setBloodOxygenText(this.getString(R.string.detection_default));
        stateViewModel.setEnvCO2Text(this.getString(R.string.detection_default));
        stateViewModel.setEnvTemperatureText(this.getString(R.string.detection_default));
        stateViewModel.setEnvTVOCText(this.getString(R.string.detection_default));
        stateViewModel.setEnvHumidityText(this.getString(R.string.detection_default));
    }

    TimeStamp timeStamp = new TimeStamp();
    boolean firstWearFlag = true;
    boolean firstEnvFlag = true;
    boolean firstBehaveFlag = true;

    private void receivedWearData(MyMqttMessage msg){
        //收到健康手环的健康监测数据后的操作
        Wear wear = JsonParse.jsonToWear(msg.getMessage());
        long millTime = wear.millTime;
        double heartRate = wear.heartBeat;
        double bloodOxygen= wear.bloodOxygen;
        double highPressure = wear.highPressure;
        double lowPressure = wear.lowPressure;
        Log.d("mqtt","接收到wear数据");
        if(firstWearFlag) {
            timeStamp.setWearBeginTimeStamp(millTime);
            firstWearFlag = false;
        }
        timeStamp.setWearEndTimeStamp(millTime);
        //TODO 刷新UI
        if(heartRate > Threshold.HEART) {
            stateViewModel.setHeartBeatState(true);
            playSound(1,0);
            sentBodyWarningDialog("您的心率过高","请稍事休息或联系他人获取帮助");
        } else stateViewModel.setHeartBeatState(false);
        if(bloodOxygen < Threshold.OXYGEN) {
            stateViewModel.setBloodOxygenState(true);
            playSound(2,0);
            sentBodyWarningDialog("您的血氧浓度过低","请稍事休息或联系他人获取帮助");
        } else stateViewModel.setBloodOxygenState(false);
        if(highPressure > Threshold.HIGH_BLOOD) stateViewModel.setHighPressureState(true);
        else stateViewModel.setHighPressureState(false);
        if(lowPressure > Threshold.LOW_BLOOD) stateViewModel.setLowPressureState(true);
        else stateViewModel.setLowPressureState(false);
        if(highPressure > Threshold.HIGH_BLOOD && lowPressure > Threshold.LOW_BLOOD) {//同时满足收缩压舒张压过高
            playSound(3,0);
            sentBodyWarningDialog("您的血压过高", "请稍事休息或联系他人获取帮助");
        }
        stateViewModel.setHeartBeatText(String.valueOf(heartRate));
        stateViewModel.setBloodOxygenText(String.valueOf(bloodOxygen));
        stateViewModel.setHighPressureText(String.valueOf((int)highPressure));
        stateViewModel.setLowPressureText(String.valueOf((int)lowPressure));
    }
    private void receivedEnvData(MyMqttMessage msg){
        //收到环境监测模块数据后的操作
        Env env = JsonParse.jsonToEnv(msg.getMessage());
        long millTime = env.millTime;
        double envTemperature = env.envTemperature;
        int envCO2 = env.envCO2;
        int envTVOC= env.envTVOC;
        double envHumidity = env.envHumidity;
        Log.d("mqtt","接收到Env数据");
        if(firstEnvFlag) {
            timeStamp.setEnvBeginTimeStamp(millTime);
            firstEnvFlag = false;
        }
        timeStamp.setEnvEndTimeStamp(millTime);

        // 刷新 UI
        if(envTemperature > Threshold.ENV_TEMP) {
            stateViewModel.setEnvTemperatureState(true);
            playSound(5,0);
            sentEnvWarningDialog("车内温度过高","请开窗通风或开启空调");
        }
        else stateViewModel.setEnvTemperatureState(false);
        if(envHumidity > Threshold.ENV_HUM) {
            stateViewModel.setEnvHumidityState(true);
            playSound(6,0);
            sentEnvWarningDialog("车内湿度过高","请开窗通风或开启外循环空调");
        }
        else stateViewModel.setEnvHumidityState(false);
        if(envCO2 > Threshold.ENV_CO2) {
            stateViewModel.setEnvCO2State(true);
            playSound(7,0);
            sentEnvWarningDialog("车内二氧化碳浓度过高","请开窗通风或开启外循环空调");
        }
        else stateViewModel.setEnvCO2State(false);
        if(envTVOC > Threshold.ENV_TVOC) {
            stateViewModel.setEnvTVOCState(true);
            playSound(8,0);
            sentEnvWarningDialog("车内有害物质浓度过高","请开窗通风或开启外循环空调");
        }
        else stateViewModel.setEnvTVOCState(false);

        stateViewModel.setEnvTemperatureText(String.valueOf(envTemperature));
        stateViewModel.setEnvCO2Text(String.valueOf(envCO2));
        stateViewModel.setEnvTVOCText(String.valueOf(envTVOC));
        stateViewModel.setEnvHumidityText(String.valueOf(envHumidity));
    }
    private void receivedBehaveData(MyMqttMessage msg){
        //收到驾驶员行为状态数据后的操作
        Behave behave = JsonParse.jsonToBehave(msg.getMessage());
        long millTime = behave.millTime;
        int cellphone = behave.cellphone;
        int yawning = behave.yawning;
        int not_buckling_up = behave.not_buckling_up;
        int both_hands_leaving_wheel = behave.both_hands_leaving_wheel;
        int eyes_closed = behave.eyes_closed;
        int head_lowered = behave.head_lowered;
        int smoke = behave.smoke;
        int no_face_mask = behave.no_face_mask;
        int not_facing_front = behave.not_facing_front;
        int sum=0;
        String dialogBody=new String("请停止以下危险行为：\n");
        Log.d("mqtt","接收到Behave数据");
        if(firstBehaveFlag) {
            timeStamp.setBehaveBeginTimeStamp(millTime);
            firstBehaveFlag = false;
        }
        timeStamp.setBehaveEndTimeStamp(millTime);

        sum=cellphone+yawning+not_buckling_up+both_hands_leaving_wheel+eyes_closed+head_lowered+smoke+no_face_mask+not_facing_front;
        if(sum==0){
            stateViewModel.setBehaveState(false);
            stateViewModel.setBehaveText("安全驾驶");
        }else{
            stateViewModel.setBehaveState(true);
            stateViewModel.setBehaveText("危险行为");
            playSound(4,0);
            if(cellphone!=0){dialogBody=dialogBody+"接打电话\n";}
            if(yawning!=0){dialogBody=dialogBody+"疲劳驾驶\n";}
            if(not_buckling_up!=0){dialogBody=dialogBody+"未系安全带\n";}
            if(both_hands_leaving_wheel!=0){dialogBody=dialogBody+"上手离开方向盘\n";}
            if(eyes_closed!=0){dialogBody=dialogBody+"闭眼\n";}
            if(head_lowered!=0){dialogBody=dialogBody+"低头\n";}
            if(smoke!=0){dialogBody=dialogBody+"抽烟\n";}
            if(no_face_mask!=0){dialogBody=dialogBody+"未佩戴口罩\n";}
            if(not_facing_front!=0){dialogBody=dialogBody+"未面向前方\n";}
            sentBodyWarningDialog("检测到危险行为",dialogBody);
        }
    }

    public void startSOSCard(){
        Intent intent = null;
        intent = new Intent(this, SOSCardActivity.class);
        intent.putExtra("data","fromNotification");
        this.startActivity(intent);
    }

    class MyMqttServiceConn implements ServiceConnection {
        private final int WEAR = 1;
        private final int ENV = 2;
        private final int BEHAVE = 3;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (MyMqttService.LocalBinder) service;
            binder.getService().setWearCallback(new MyMqttService.WearCallback() {
                @Override
                public void wearDataChanged(MyMqttMessage myMqttMessage) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mqttMessage",myMqttMessage);
                    msg.setData(bundle);
                    msg.what = WEAR;
                    //发送通知
                    handler.sendMessage(msg);
                }
            });
            binder.getService().setBehaveCallback(new MyMqttService.BehaveCallback() {
                @Override
                public void behaveDataChanged(MyMqttMessage myMqttMessage) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mqttMessage",myMqttMessage);
                    msg.setData(bundle);
                    msg.what = BEHAVE;
                    //发送通知
                    handler.sendMessage(msg);
                }
            });
            binder.getService().setEnvCallback(new MyMqttService.EnvCallback() {
                @Override
                public void envDataChanged(MyMqttMessage myMqttMessage) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("mqttMessage",myMqttMessage);
                    msg.setData(bundle);
                    msg.what = ENV;
                    //发送通知
                    handler.sendMessage(msg);
                }
            });
        }

        @SuppressLint("HandlerLeak")
        Handler handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                MyMqttMessage myMqttMessage = (MyMqttMessage)msg.getData().getSerializable("mqttMessage");
                String str_msg = myMqttMessage.getMessage();
                String str_topic = myMqttMessage.getTopic();
                Log.d("mqtt","handle message:\n"+str_msg);
                switch (msg.what){
                    case WEAR:
                        receivedWearData(myMqttMessage);
                        break;
                    case BEHAVE:
                        receivedBehaveData(myMqttMessage);
                        break;
                    case ENV:
                        receivedEnvData(myMqttMessage);
                        break;
                }
            }
        };


        @Override
        public void onServiceDisconnected(ComponentName name) {
            binder = null;
        }
    }


    @Override
    protected void onDestroy(){
        super.onDestroy();
        // 清除动画，如果有
        if (tv1 != null) tv1.clearAnimation();
        if (tv2 != null) tv2.clearAnimation();
        if (tv3 != null) tv3.clearAnimation();
    }

    public void setDrivingBtnListener(TextView tv){
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv1://finishBtn
                        ISSTARTUP = true;
                        hiddenAnim1.start();
//                apperaAnim2.start_bg();
                        hiddenAnim3.start();
                        onRecordStop(drivingTimer);
                        //TODO 在这里添加保存历史记录的操作
                        mqttService.publish("ESP32_env_E0001_off","1");
                        mqttService.publish("ESP32_wear_W0001_off","1");
                        mqttService.publish("switch_behave_off_04EA56902CB0","1");
                        finish();
                        String envBegin = String.valueOf(timeStamp.getEnvBeginTimeStamp());
                        String envEnd = String.valueOf(timeStamp.getEnvEndTimeStamp());
                        Log.d("mqtt","timeBegin:"+envBegin);
                        Log.d("mqtt","timeEnd:"+envEnd);
                        addHistory();
                        //TODO 在这里添加保存历史记录的操作
                        break;
                    case R.id.tv2://pauseBtn
                        ISSTARTUP = false;
                        apperaAnim1.start();
                        hiddenAnim2.start();
                        apperaAnim3.start();
                        onRecordPause(drivingTimer);
                        System.out.println("tv2 clicked!");
                        break;
                    case R.id.tv3://continueBtn
                        ISSTARTUP = true;
                        hiddenAnim1.start();
                        apperaAnim2.start();
                        hiddenAnim3.start();
                        onRecordStart(drivingTimer);
                        System.out.println("tv3 clicked!");
                        break;
                    default:
                        break;
                }
            }
        });
    }

    private long recordingTime = 0;// 记录下来的总时间
    public void onRecordStart(Chronometer recordChronometer) {
        recordChronometer.setBase(SystemClock.elapsedRealtime() - recordingTime);// 跳过已经记录了的时间，起到继续计时的作用
        recordChronometer.start();
    }
    public void onRecordPause(Chronometer recordChronometer) {
        recordChronometer.stop();
        recordingTime = SystemClock.elapsedRealtime()- recordChronometer.getBase();// 保存这次记录了的时间
    }
    public void onRecordStop(Chronometer recordChronometer) {
        recordingTime = 0;
        recordChronometer.setBase(SystemClock.elapsedRealtime());
    }

    private void addHistory() {
        IotdbOperation iotdbOperation = new IotdbOperation();
        ShareData shareData = (ShareData)getApplication();
        timeStamp.setUserId(shareData.userId);
        try {
            iotdbOperation.SessionStart(timeStamp);
        } catch (IoTDBConnectionException e) {
            e.printStackTrace();
        } catch (StatementExecutionException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建出现动画
     */
    public void setApperaAnimationView() {

        apperaAnim1 = ValueAnimator.ofFloat(tv1.getHeight() * 2, 0);
        apperaAnim1.setDuration(500);
        apperaAnim1.setTarget(tv1);
        apperaAnim1.addUpdateListener(animation -> tv1.setTranslationY((Float) animation.getAnimatedValue()));
        apperaAnim1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv1.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv1.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv1.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });


        apperaAnim2 = ValueAnimator.ofFloat(tv2.getHeight() * 2, 0);
        apperaAnim2.setDuration(500);
        apperaAnim2.setTarget(tv2);
        apperaAnim2.addUpdateListener(animation -> tv2.setTranslationY((Float) animation.getAnimatedValue()));
        apperaAnim2.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv2.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv2.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv2.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        apperaAnim3 = ValueAnimator.ofFloat(tv3.getHeight() * 2, 0);
        apperaAnim3.setDuration(500);
        apperaAnim3.setTarget(tv3);
        apperaAnim3.addUpdateListener(animation -> tv3.setTranslationY((Float) animation.getAnimatedValue()));
        apperaAnim3.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv3.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv3.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv3.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    /**
     * 创建消失动画
     */
    public void setHiddenAnimationView() {

        hiddenAnim1 = ValueAnimator.ofFloat(0, tv1.getHeight() * 2);
        hiddenAnim1.setDuration(500);
        hiddenAnim1.setTarget(tv1);
        hiddenAnim1.addUpdateListener(animation -> tv1.setTranslationY((Float) animation.getAnimatedValue()));
        hiddenAnim1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv1.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv1.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv1.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        hiddenAnim2 = ValueAnimator.ofFloat(0, tv2.getHeight() * 2);
        hiddenAnim2.setDuration(500);
        hiddenAnim2.setTarget(tv2);
        hiddenAnim2.addUpdateListener(animation -> tv2.setTranslationY((Float) animation.getAnimatedValue()));
        hiddenAnim2.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv2.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv2.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv2.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        hiddenAnim3 = ValueAnimator.ofFloat(0, tv3.getHeight() * 2);
        hiddenAnim3.setDuration(500);
        hiddenAnim3.setTarget(tv3);
        hiddenAnim3.addUpdateListener(animation -> tv3.setTranslationY((Float) animation.getAnimatedValue()));
        hiddenAnim3.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                tv3.setEnabled(false);
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                tv3.setEnabled(true);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                tv3.setEnabled(true);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
    }

    public void sentBodyWarningDialog(String title,String body){
        if(alertDialog!=null)alertDialog.dismiss();
        alertDialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setCancelable(true)
                .setIcon(R.drawable.warning)
                .setMessage(body)
                .setPositiveButton("联系紧急联系人", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(DrivingDetectionActivity.this, "即将呼叫紧急联系人", Toast.LENGTH_SHORT).show();
                        callTel("18525301819");
                        sendMsg("18525301819",getString(R.string.sos_message));
                    }
                })
                .create();
        alertDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                alertDialog.dismiss();
            }
        }, 5000);
    }
    public void sentSOSDialog(){
        if(alertDialog!=null)alertDialog.dismiss();
        alertDialog = new AlertDialog.Builder(this)
                .setTitle("紧急情况")
                .setCancelable(false)
                .setIcon(R.drawable.warning)
                .setMessage("正在通知紧急联系人")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .create();
        alertDialog.show();
        callTel("18525301819");
        sendMsg("18525301819",getString(R.string.sos_message));
    }
    public void sentEnvWarningDialog(String title,String body){
        if(alertDialog!=null)alertDialog.dismiss();
        alertDialog = new AlertDialog.Builder(this)
                .setTitle(title)
                .setCancelable(true)
                .setIcon(R.drawable.environment)
                .setMessage(body)
                .create();
        alertDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                alertDialog.dismiss();
            }
        }, 5000);
    }

    private void initSound(){
        soundPoolMap.put(1, soundPool.load(this, R.raw.heart_caution, 1));
        soundPoolMap.put(2, soundPool.load(this, R.raw.oxy_caution, 2));
        soundPoolMap.put(3, soundPool.load(this, R.raw.pressure_caution, 3));
        soundPoolMap.put(4, soundPool.load(this, R.raw.behave_caution, 4));
        soundPoolMap.put(5, soundPool.load(this, R.raw.temp_warninig, 5));
        soundPoolMap.put(6, soundPool.load(this, R.raw.humidity_warning, 6));
        soundPoolMap.put(7, soundPool.load(this, R.raw.co2_warning, 7));
        soundPoolMap.put(8, soundPool.load(this, R.raw.tvoc_warning, 8));
        soundPoolMap.put(9, soundPool.load(this, R.raw.time_caution, 9));

    }
    private void playSound(int sound, int loop) {
        soundPool.play(soundPoolMap.get(sound), 1, 1, 1, loop, 1f);
        //参数：1、Map中取值   2、左声道音量     3、右声道音量  4、优先级   5、重播次数   6、播放速度
    }
    private void callTel(String tel){
        //拨号界面的action,传入Intent中
        /*String action = "android.intent.action.DIAL";*/
        String action = Intent.ACTION_CALL;
        Intent intent = new Intent(action);
        //携带数据
        String number = tel;
        intent.setData(Uri.parse("tel:" + number));
        //start
        startActivity(intent);
    }
    private void sendMsg(String tel,String message){
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:" + tel))
                .putExtra("sms_body", message);
        startActivity(intent);
    }
}